package com.sea.base.ext.global

/**
 * 如果[check]为true，则抛出异常
 */
inline fun throwIf(st: String, e: Throwable? = null, check: () -> Boolean) {
    if (check.invoke()) {
        throw IllegalArgumentException(st, e)
    }
}

@JvmOverloads
inline fun throwIfDebug(st: String, e: Throwable? = null, check: () -> Boolean = { true }) {
    if (isDebug) {
        throwIf(st, e, check)
    }
}

/**
 * 如果是debug才会执行，防止在release额外消耗资源，主要用于高并时减少测试代码的消耗
 */
inline fun ifDebug(call: () -> Unit) {
    if (isDebug) {
        call.invoke()
    }
}

const val CAUSE_CAPTION = "Caused by: "
const val SUPPRESSED_CAPTION = "Suppressed: "

/**
 * 打印详细的堆栈日志，不会简化
 */
fun Throwable.stackTraceToStringDetail(): String {
    val builder = StringBuilder(this.stackTraceToString()).append("\nCaused详情：")
    this.suppressed.forEach {
        appendError(builder, it)
    }
    appendError(builder, this.cause)
    return builder.toString()
}

private fun appendError(builder: StringBuilder, ex: Throwable?) {
    if (ex == null) return
    builder.append("\n").append(CAUSE_CAPTION).append("\t").append(ex.toString())
    ex.stackTrace.forEach {
        builder.append("\n\tat ").append(it.toString())
    }
    ex.suppressed.forEach {
        appendError(builder, it)
    }
    appendError(builder, ex.cause)
}